<?php
namespace newMobile\Controller;

use Think\Controller;

class UsersApiController extends Controller
{
    public function _initialize()
    {
        //parent::_initialize();
        header('Content-Type:application/json;charset=utf-8 ');
        vendor('Weixinpay.WxPayPubHelper');
        $redis = connectRedis();
        $rdsession = I('post.token');
        $uidString = $rdsession . 'uid';
        $uuid = $redis->get($uidString);
        $store_id = intval($_POST["store_id"]);
        if (empty($store_id)) {
            $storeString = $rdsession . 'storeId';
            $store_id = $redis->get($storeString);
        }
        $redis = connectRedis();
        $rs1 = $redis->get($rdsession);
        $rs = json_decode($rs1, TRUE);
        $openid = $rs['openid'];
        $loginString = $openid.'login';
        $is_login=$redis->get($loginString);
        if ($is_login) {
            $user_rtopenid = M('users_rtopenid')->where("rtopenid='" . $openid . "'")->find();
            $uid = $user_rtopenid['uid'];
        }
        //$user_rtopenid = M('users_rtopenid')->where("rtopenid='" . $openid."'")->find();
        /*file_put_contents("session.txt", date("Y-m-d H:i:s") . "UsersApi_post  " . print_r($_POST, true) . "\r\n", FILE_APPEND);
        file_put_contents("session.txt", date("Y-m-d H:i:s") . "初始化sql2  " . print_r(M('users_rtopenid')->getLastSql(), true) . "\r\n", FILE_APPEND);
        file_put_contents("session.txt", date("Y-m-d H:i:s") . "user_rtopenid2  " . print_r($user_rtopenid, true) . "\r\n", FILE_APPEND);
        file_put_contents("session.txt", date("Y-m-d H:i:s") . "user_rtopenid['uid']2  " . print_r($user_rtopenid['uid'], true) . "\r\n", FILE_APPEND);
       */// $uid=$user_rtopenid['uid'];
        if(empty($uid)){
            $uid=$uuid;
        }
        /*if(empty($uid)){
            $this->ajax_r(0, '用户信息已失效！');
        }
        if(empty($store_id)){
            $this->ajax_r(0, '店铺信息已失效！');
        }*/
        $member_info=M('member')->where('user_id='.$uid.' and store_id='.$store_id)->find();
        $this->member_id = $member_info['id'];
        //file_put_contents("session.txt", date("Y-m-d H:i:s") . "uid  " . print_r($uid, true) . "\r\n", FILE_APPEND);
        $this->uid = $uid;
        $this->store_id = $store_id;
    }

    public function login(){
        file_put_contents("session.txt", date("Y-m-d H:i:s") . "login  " .print_r('执行login', true). "\r\n", FILE_APPEND);
        if($_POST){
            $users=M('users');
            $post=I('post.');
            $phone=$post['mobile'];
            if (empty($phone)) {
                $this->ajax_r(0, '账号不能为空！');
            }
            if (empty($post['type'])) {
                $this->ajax_r(0, '请选择一个登录方式！');
            }
            $type=$post['type']?$post['type']:2;
            if($type==1){//两种方式登录，1密码2验证码
                $password=$post['password'];
                if (empty($password)) {
                    $this->ajax_r(0, '密码不能为空！');
                }
               /* $pass1=passport_encrypt($password,'wnsc');
                file_put_contents("login.txt", date("Y-m-d H:i:s") . "加密后  " .print_r($pass1, true). "\r\n", FILE_APPEND);
                */
                $userinfo=$users->where('phone="'.$phone.'"')->find();
                if(empty($userinfo)){
                    $this->ajax_r(0,'用户不存在！');
                }else{
                    $pass=passport_decrypt($userinfo['password'],'wnsc');
                    if(!$pass==$password){
                        $this->ajax_r(0,'密码错误！');
                    }
                }
            }else{
                $sms_captcha = $post['code'];
                if (empty($sms_captcha)) {
                    $this->ajax_r(0, '验证码不能为空！');
                }
                $userinfo=$users->where('phone="'.$phone.'"')->find();
                $redis = connectRedis();
                $code = $redis->get($phone);
                if(!($code == $sms_captcha)) {
                  $this->ajax_r(0, '验证码失效！');
                }
            }
            $rdsession =$post['token'];
            $redis = connectRedis();
            $rs1 = $redis->get($rdsession);
            $rs = json_decode($rs1, TRUE);
            $openid = $rs['openid'];
            $uid=$this->uid;
            $mobileUser = M('users')->find($uid);
            if($userinfo){//已有账号，若已绑定openid，删掉当前uid 若未绑定openid则将openid添加，删掉当前uid
                $user_rtopenid = M('users_rtopenid')->where("rtopenid='" . $openid. "' and uid=".$userinfo['id'])->find();
                if (empty($user_rtopenid))  { //未绑定openid
                    $info['id'] = $userinfo['id'];
                    if($userinfo['wx_name']!==$mobileUser['wx_name']){
                        $info['wx_name'] = $mobileUser['wx_name'];
                        M('users')->save($info);
                    }
                    $rtopenid_info['rtopenid'] = $openid;
                    $rtopenid_info['uid'] = $userinfo['id'];
                    M('users_rtopenid')->add($rtopenid_info);
                }
                M('users')->where('id=' . $uid)->delete();
                M('users_rtopenid')->where('uid=' . $uid)->delete();
                $now_uid = $userinfo['id'];
             }else{//暂无账号，将当前uid绑定phone，若未绑定openid则将openid添加
                $user_rtopenid = M('users_rtopenid')->where("rtopenid='" . $openid. "' and uid=".$uid)->find();
                $info['id'] = $uid;
                $info['phone'] = $phone;
                $rs = M('users')->save($info);
                if($rs){
                    if(empty($user_rtopenid)){  //未绑定openid
                        $rtopenid_info['rtopenid'] = $openid;
                        $rtopenid_info['uid'] = $uid;
                        M('users_rtopenid')->add($rtopenid_info);
                    }
                }
                $now_uid = $uid;
            }
            $user=M('users')->find($now_uid);
            $token = $post['token'];
            $uidString = $token. 'uid';
            $uidNameString = $token. 'user_name';
            $uidPicString = $token. 'user_pic';
            $loginString = $openid.'login';
            $redis->set($uidString,$now_uid);
            $redis->set($uidNameString,$user['username']);
            $redis->set($uidPicString, $user['user_pic']);
            $redis->set($loginString, 1);
            $date_time=date('Y-m-d H:i:s', time());
            $login_info['id']=$now_uid;
            $login_info['login_time']=$date_time;
            M('users')->save($login_info);
            unset($user['id']);
            $data['user'] = $user;
            $data['is_login'] = 1;
            $this->ajax_r(1,'登录成功！',$user);
        }
    }
    public function is_login()
    {
        if ($_POST) {
            $rdsession = I('post.token');
            $redis = connectRedis();
            $rs1 = $redis->get($rdsession);
            $rs = json_decode($rs1, TRUE);
            $openid = $rs['openid'];
            $uid = $this->uid;
            if (empty($uid)) {
                $this->ajax_r(0, '用户信息已失效');
            }
            $userInfo = M('users')->find($uid);
            if (empty($userInfo)) {
                $this->ajax_r(0, '该用户不存在！');
            }
            $loginString = $openid.'login';
            $is_login=$redis->get($loginString);
            if ($is_login) {
                $data['is_login'] = 1;
                $this->ajax_r(1, '你已登录！', $data);
            }else {
                $this->ajax_r(0, '未登录');
            }
        }
    }
    public function login_out(){
        $token=I('post.token');
        $redis = connectRedis();
        $rs1 = $redis->get($token);
        $rs = json_decode($rs1, TRUE);
        $openid = $rs['openid'];
        $loginString = $openid.'login';
        $uidString = $token. 'uid';
        $uidNameString = $token. 'user_name';
        $redis->set($uidString, null);
        $redis->set($uidNameString,null);
        $redis->set($loginString, null);
        $this->ajax_r(1,'退出成功');
    }

    public function sendCode()
    {
        $data = I('post.');
        $moblie = $data['phone'];
        $code = rand(1000, 9999);
        $rs = duanxin($code, $moblie);
        if ($rs['resultcode'] == 0) {
            $redis = connectRedis();
            $redis->set($moblie, $code);
            $this->ajax_r(1, '发送成功！');
        } else {
            $data['error'] = $rs['errordescription'];
            $this->ajax_r(0, '发送失败！', $data);
        }
    }

    public function mobile_yz(){
        if($_POST) {
            $phone = I('post.mobile');
            if (empty($phone)) {
                $this->ajax_r(0, '', '用户不存在！');
            }
            file_put_contents("login.txt", date("Y-m-d H:i:s") . "phone1  " .print_r($phone, true). "\r\n", FILE_APPEND);
            $token = I('post.token');
            file_put_contents("login.txt", date("Y-m-d H:i:s") . "token1  " .print_r($token, true). "\r\n", FILE_APPEND);

            $redis = connectRedis();
            $users = M('users');
            $rs = $users->where('phone="' . $phone . '" and ishidden=1')->find();
            if ($rs) {
                $forgetUserString = $token . 'forget_user';
                file_put_contents("login.txt", date("Y-m-d H:i:s") . "forgetUserString1  " .print_r($forgetUserString, true). "\r\n", FILE_APPEND);
                $redis->set($forgetUserString, $phone);
                $this->ajax_r(1,'用户存在！');
            } else {
                $this->ajax_r(0,'用户不存在！');
            }
        }
    }
    public function pwd_sendCode(){
        $token = I('post.token');
        file_put_contents("login.txt", date("Y-m-d H:i:s") . "token2  " .print_r($token, true). "\r\n", FILE_APPEND);
        $redis = connectRedis();
        $forgetUserString = $token . 'forget_user';
        file_put_contents("login.txt", date("Y-m-d H:i:s") . "forgetUserString2  " .print_r($forgetUserString, true). "\r\n", FILE_APPEND);

        $moblie= $redis->get($forgetUserString);
        file_put_contents("login.txt", date("Y-m-d H:i:s") . "phone2  " .print_r($moblie, true). "\r\n", FILE_APPEND);
        if($moblie){
            $code=rand(1000,9999);
            $rs=duanxin($code,$moblie);
            if($rs['resultcode']==0){
                $forgetCodeString = $token.'forget_pwd_code';
                $redis->set($forgetCodeString, $code);
                $this->ajax_r(1,'发送成功！');
            }else{
                $this->ajax_r(0,'发送失败！',$rs['errordescription']);
            }
        }else{
            $this->ajax_r(0,'验证手机不存在,请重新验证！');
        }

    }
    public function code_yanzheng(){
        if($_POST){
            $token = I('post.token');
            $redis = connectRedis();
            $forgetUserString = $token . 'forget_user';
            $moblie= $redis->get($forgetUserString);
            $forgetCodeString = $token.'forget_pwd_code';
            if($moblie){
                $sms_captcha=I('post.code');
                $code=$redis->get($forgetCodeString);
                if($sms_captcha==$code){
                    $this->ajax_r(1,'验证码验证成功！');
                }else{
                    $this->ajax_r(0,'验证码错误！');
                }
            }else{
                session('step','1');
                $this->ajax_r(0,'验证手机不存在,请重新验证！');
            }
        }
    }

    public function pwd_rest()
    {
        $token = I('post.token');

        file_put_contents("login.txt", date("Y-m-d H:i:s") . "token3  " .print_r($token, true). "\r\n", FILE_APPEND);
        $redis = connectRedis();
        $forgetUserString = $token . 'forget_user';
        file_put_contents("login.txt", date("Y-m-d H:i:s") . "forgetUserString3  " .print_r($forgetUserString, true). "\r\n", FILE_APPEND);

        $moblie= $redis->get($forgetUserString);
        file_put_contents("login.txt", date("Y-m-d H:i:s") . "phone3  " .print_r($moblie, true). "\r\n", FILE_APPEND);

        $forgetCodeString = $token . 'forget_pwd_code';
        if ($moblie) {
            $pwd = I('post.password');
            $data['password'] = passport_encrypt($pwd, 'wnsc');
            $users = M('users');
            file_put_contents("login.txt", date("Y-m-d H:i:s") . "data  " .print_r($data, true). "\r\n", FILE_APPEND);
            $rs = $users->where("phone=$moblie")->save($data);
            file_put_contents("login.txt", date("Y-m-d H:i:s") . "sql  " .print_r($users->getLastSql(), true). "\r\n", FILE_APPEND);
            if ($rs) {
                $redis->set($forgetUserString, null);
                $redis->set($forgetCodeString, null);
                $this->ajax_r(1,'密码重置成功！');
            } else {
                $this->ajax_r(0,'密码重置失败！');
            }
        } else {
            $this->ajax_r(0,'验证手机不存在,请重新验证！');
        }
    }
    //解密
    public function jiemi()
    {
        $password = I('get.pass');
        $pass = passport_decrypt($password, 'wnsc');
        $datas['message'] = '成功';
        $datas['datas'] = $pass;
        $datas['status'] = 1;
        $datas = json_encode($datas);
        die($datas);
    }

    public function editUserInfo()
    {
        $users = M('users');
        $user_id = session('user_id');
        $data = I('post.');
        $info['id'] = $user_id;
        if(!empty($data['nickname'])){
            $info['username'] = $data['nickname'];
        }
        if(!empty($data['sex'])){
            $info['sex'] = $data['sex'];
        }
        if(!empty($data['birthday'])){
            $info['birthday'] = $data['birthday'];
        }
        if(!empty($data['user_pic'])){
            $info['user_pic'] = $data['user_pic'];
        }
        $rs = $users->save($info);
        $userinfo=$users->find($user_id);
        if ($rs) {
            $datas['status'] = 1;
            $datas['message'] = '修改成功';
            $datas['datas'] = $userinfo;
            $datas = json_encode($datas);
            die($datas);
        } else {
            $this->ajax_r(0, '修改失败！');
        }

    }
    public function addAddress(){
        if($_POST){
            $user_id = $this->uid;
            $users_address=M('users_address');
            $is_default=M('users_address')->where("user_id=$user_id and is_default=1")->select();
            $data=I('post.');
            $newdata['user_id']=$user_id;
            $newdata['consigner']=$data['name'];
            $newdata['province']=$data['province_id'];
            $newdata['city']=$data['city_id'];
            $newdata['district']=$data['district_id'];
            $newdata['address']=$data['address_detail'];
            $newdata['mobile']=$data['mobile'];
            if(!$is_default){
                $newdata['is_default']=1;
            }
            if($data['address_id']!=0){
                $newdata['address_id']=$data['address_id'];
                $rs=$users_address->save($newdata);
                if($rs){
                    $this->ajax_r('1','更新成功');
                }else{
                    $this->ajax_r('0','更新失败');
                }
            }else{
                $rs=$users_address->add($newdata);
                if($rs){
                    $this->ajax_r('1','添加成功');
                }else{
                    $this->ajax_r('0','添加失败');
                }
            }
        }
    }
    public function setdefault(){
        $address_id=I('post.address_id');
        $user_id= $this->uid;
        $users_address=M('users_address');
        $users_address-> where('user_id='.$user_id)->setField('is_default',0);
        $users_address-> where('address_id='.$address_id)->setField('is_default',1);
        $this->ajax_r('1','设置默认成功');
    }

    public function addressdelete(){
        $id=I('post.address_id');
        $user_id= $this->uid;
        $users_address=M('users_address');
        $address=$users_address-> where('user_id='.$user_id.' and address_id='.$id)->find();
        if(empty($address)){
            $this->ajax_r('0','地址不存在');
        }
        $rs=$users_address->delete($id);
        if($rs){
            $this->ajax_r('1','删除成功');
        }else{
            $this->ajax_r('0','删除失败');
        }
    }
    /**
     * 获取省列表
     */
    public function getProvince()
    {
        $province_list = getProvinceList();
        $this->ajax_r('1','成功',$province_list);
    }


    /**
     * 获取城市列表
     *
     * @return Ambigous <multitype:\think\static , \think\false, \think\Collection, \think\db\false, PDOStatement, string, \PDOStatement, \think\db\mixed, boolean, unknown, \think\mixed, multitype:, array>
     */
    public function getCity()
    {

        $province_id = isset($_POST['province_id']) ? $_POST['province_id'] : 0;
        $city_list = getCityList($province_id);
        $this->ajax_r('1','成功',$city_list);

    }

    /**
     * 获取区域地址
     */
    public function getDistrict()
    {
        $city_id = isset($_POST['city_id']) ? $_POST['city_id'] : 0;
        $district_list = getDistrictList($city_id);
        $this->ajax_r('1','成功',$district_list);
    }

    public function getUserIndex(){
    $order=M('order');
    $store_id = $this->store_id;
    $uid = $this->uid;
    if($uid){
        //红包
        $daiyan=get_userdaiyan_list($uid);
        $daiyan_price=0;
        foreach($daiyan as $key=>$value){
            $daiyan_price=$daiyan_price+$value['recommend_price'];
        }
        $data['daiyan_price']=$daiyan_price;
        //未付款
        $wcount=$order->where('buyer_id='.$uid. ' and  store_id='.$store_id.' and order_state="10" and refund_state=0 and tuanselect=0')->count();
        //待拼团
        $dptcount=$order->where('buyer_id='.$uid. ' and  store_id='.$store_id.' and order_state="20" and refund_state=0 and tuanselect=1 and tuan_is_success=0')->count();
        //已付款待发货
        $dfcount=$order->where('buyer_id='.$uid. ' and  store_id='.$store_id.' and order_state="20" and refund_state=0 and tuanselect=0')->count();
        //拼团成功
        $ptcount=$order->where('buyer_id='.$uid. ' and  store_id='.$store_id.' and order_state="20" and refund_state=0 and tuanselect=1 and tuan_is_success=1')->count();
        $dfcount=$dfcount+$ptcount;
        //已发货待收货
        $dscount=$order->where('buyer_id='.$uid. ' and  store_id='.$store_id.' and order_state="30" and refund_state=0 and tuanselect=0')->count();
        //待评价
        $dpcount=$order->where('buyer_id='.$uid. ' and  store_id='.$store_id.' and order_state="40" and  tuanselect=0 and refund_state="0" and evaluation_state="0"')->count();
        //退换货
        $thcount=$order->where('buyer_id='.$uid. ' and  store_id='.$store_id.' and  refund_state>0 and refund_state<5 ')->count();
        $member_info=M('member')->where('user_id='.$uid.' and store_id='.$store_id)->find();
        $user=M('users')->find($uid);
        $data['thcount']=$thcount;
        $data['wcount']=$wcount;
        $data['dptcount']=$dptcount;
        $data['dfcount']=$dfcount;
        $data['dscount']=$dscount;
        $data['dpcount']=$dpcount;
        $data['member']=$member_info;
        $data['user']=$user;
        $this->ajax_r('1','成功',$data);
    }else{
        $this->ajax_r('0','用户信息已失效');
    }
}

    public function getOrderList()
    {
        $order = M('order');
        $uid = $this->uid;
        $store_id = $this->store_id;
        if ($uid) {
            $lastId = intval(I('post.lastId'));
            $Num = trim(I('post.num', 6));
            if (!empty($lastId)) {
                $orderdetails = $order->field('yt_order.order_id')->find($lastId);
                if (empty($orderdetails)) {
                    $this->ajax_r(0, '最后ID参数错误！');
                }
            }
            //未付款
            $wcount = $order->where('buyer_id=' . $uid . ' and  store_id='.$store_id.' and order_state="10" and refund_state=0 and tuanselect=0')->count();
            //待拼团
            $dptcount = $order->where('buyer_id=' . $uid .' and  store_id='.$store_id. ' and order_state="20" and refund_state=0 and tuanselect=1 and tuan_is_success=0')->count();
            //已付款待发货
            $dfcount = $order->where('buyer_id=' . $uid .' and  store_id='.$store_id. ' and order_state="20" and refund_state=0 and tuanselect=0')->count();
            //拼团成功
            $ptcount = $order->where('buyer_id=' . $uid .' and  store_id='.$store_id. ' and order_state="20" and refund_state=0 and tuanselect=1 and tuan_is_success=1')->count();
            $dfcount = $dfcount + $ptcount;
            //已发货待收货
            $dscount = $order->where('buyer_id=' . $uid .' and  store_id='.$store_id. ' and order_state="30" and refund_state=0 and tuanselect=0')->count();
            //待评价
            $dpcount = $order->where('buyer_id=' . $uid .' and  store_id='.$store_id. ' and order_state="40" and  tuanselect=0 and refund_state="0" and evaluation_state="0"')->count();
            //退换货
            $thcount = $order->where('buyer_id=' . $uid .' and  store_id='.$store_id. ' and  refund_state>0 and refund_state<5 ')->count();
            $count = $order->where('buyer_id=' . $uid.' and  store_id='.$store_id)->count();
            $data['count']=$count;
            $data['thcount'] = $thcount;
            $data['wcount'] = $wcount;
            $data['dptcount'] = $dptcount;
            $data['dfcount'] = $dfcount;
            $data['dscount'] = $dscount;
            $data['dpcount'] = $dpcount;

            $where['buyer_id'] = $uid;
            $where['store_id'] = $store_id;
            $where['refund_state'] = '0';
            if (I('post.status') == 1) {
                //待付款
                $where['order_state'] = '10';

            }
            if (I('post.status') == 2) {
                //待拼单
                $where['order_state'] = '20';
                $where['tuanselect'] = 1;
                $where['tuan_is_success'] = 0;
                $where['refund_state'] = '0';
            }
            if (I('post.status') == 3) {
                //待发货
                $where['_string'] = ' (order_state="20" and tuanselect=0)  OR ( order_state="20" and tuanselect=1 and tuan_is_success=1) ';
                $where['refund_state'] = '0';
            }
            if (I('post.status') == 4) {
                //待收货
                $where['order_state'] = '30';
                $where['refund_state'] = '0';
            }
            if (I('post.status') == 5) {
                //待评价
                $where['order_state'] = '40';
                $where['evaluation_state'] = '0';
            }
            if (!empty($lastId)) {
                $where['_string'] = ' order_id<"' . $lastId . '" ';
            }
            $order_list = $order->where($where)->limit(0, $Num)->order('order_id desc')->select();
            foreach ($order_list as $key => $value) {
                if ($value['tuanselect'] == 0) {
                    if ($value['refund_state'] == 0) {
                        if ($value['order_state'] == '0') {
                            $order_list[$key]['top_info'] = '已取消';
                            $order_list[$key]['button']['0'] = '已取消';
                        }
                        if ($value['order_state'] == '10') {
                            $order_list[$key]['top_info'] = '等待付款';
                            $order_list[$key]['button']['0'] = '取消订单';
                            $order_list[$key]['button']['1'] = '立即付款';
                        }
                        if ($value['order_state'] == '20') {
                            $order_list[$key]['top_info'] = '已付款，待发货';
                            $order_list[$key]['button']['0'] = '退款/退货';
                        }
                        if ($value['order_state'] == '30') {
                            $order_list[$key]['top_info'] = '已发货，待收货';
                            $order_list[$key]['button']['0'] = '退款/退货';
                            $order_list[$key]['button']['1'] = '确认收货';
                        }
                        if ($value['order_state'] == '40' && $value['evaluation_state'] == '0') {
                            $order_list[$key]['top_info'] = '已收货，待评价';
                            $endtime = $value['finnshed_time'] + 60 * 60 * 24 * 7;
                            $nowtime = time();
                            if ($nowtime < $endtime) {
                                $order_list[$key]['button']['0'] = '退款/退货';
                            }
                            $order_list[$key]['button']['1'] = '立即评价';
                        }
                    } else {
                        if ($value['refund_state'] == 1) {
                            $order_list[$key]['top_info'] = '退款中';
                            $order_list[$key]['button']['0'] = '退款中';
                        }
                        if ($value['refund_state'] == 2) {
                            $order_list[$key]['top_info'] = '同意退款';
                            $order_list[$key]['button']['0'] = '同意退款';
                        }
                        if ($value['refund_state'] == 3) {
                            $order_list[$key]['top_info'] = '拒绝退款';
                            $order_list[$key]['button']['0'] = '拒绝退款';
                        }
                        if ($value['refund_state'] == 4) {
                            $order_list[$key]['top_info'] = '等待财务待打款';
                            $order_list[$key]['button']['0'] = '待打款';
                        }
                        if ($value['refund_state'] == 5) {
                            $order_list[$key]['top_info'] = '退款完成';
                            $order_list[$key]['button']['0'] = '退款完成';
                        }
                        if ($value['order_state'] == '40' && $value['evaluation_state'] == '0') {
                            $order_list[$key]['top_info'] = '已收货，待评价';
                            $endtime = $value['finnshed_time'] + 60 * 60 * 24 * 7;
                            $nowtime = time();
                            if ($nowtime < $endtime) {
                                $order_list[$key]['button']['0'] = '退款/退货';
                            }
                            $order_list[$key]['button']['1'] == '立即评价';
                        }
                    }
                } else {
                    //已取消团购订单
                    if ($value['order_state'] == '0') {
                        $order_list[$key]['top_info'] = '已取消';
                        $order_list[$key]['button']['0'] = '已取消';
                    }
                    if ($value['refund_state'] == '0') {
                        if ($value['order_state'] == '10') {
                            $order_list[$key]['top_info'] = '等待付款';
                            $order_list[$key]['button']['0'] = '取消订单';
                            $order_list[$key]['button']['1'] = '立即付款';
                        }
                        if ($value['order_state'] == '20') {
                            if ($value['tuanselect'] == 1) {
                                if ($value['tuan_is_first_id'] == 0) {
                                    $num = get_tuan($value['order_id']);
                                } else {
                                    $num = get_tuan($value['tuan_is_first_id']);
                                }
                                if ($num < $value['tuannum']) {
                                    $tuan_type = '拼团中';
                                } else {
                                    $tuan_type = '拼团成功';
                                }

                            }
                            $order_list[$key]['top_info'] = '已付款，待发货';
                            $order_list[$key]['button']['0'] = $tuan_type;
                        }
                        if ($value['order_state'] == '30') {
                            $order_list[$key]['top_info'] = '已发货，待收货';
                            $order_list[$key]['button']['0'] = '确认收货';
                        }
                        if ($value['order_state'] == '40' && $value['evaluation_state'] == '0') {
                            $order_list[$key]['top_info'] = '已收货，待评价';
                            $order_list[$key]['button']['0'] = '立即评价';
                        }
                    } else {
                        if ($value['refund_state'] == '1') {
                            $order_list[$key]['top_info'] = '退款中';
                            $order_list[$key]['button']['0'] = '退款中';
                        }
                        if ($value['refund_state'] == '2') {
                            $order_list[$key]['top_info'] = '同意退换货';
                            $order_list[$key]['button']['0'] = '同意退换货';
                        }
                        if ($value['refund_state'] == '3') {
                            $order_list[$key]['top_info'] = '商家拒绝';
                            $order_list[$key]['button']['0'] = '商家拒绝';
                        }
                        if ($value['refund_state'] == '4') {
                            $order_list[$key]['top_info'] = '退款/货完成';
                            $order_list[$key]['button']['0'] = '退款/货完成';
                        }
                    }
                }
                if ($value['shipping_fee'] != 0) {
                    $order_list[$key]['shipping_fee'] = '运费：￥' . $value['shipping_fee'];
                } else {
                    $order_list[$key]['shipping_fee'] = '免邮';
                }
                $shop_list = get_order_shop($value['order_id']);
                $order_list[$key]['shop_list'] = $shop_list;
                $youhui_price = get_coupon_price($value['buyer_id'], $value['coupon']);
                $order_amount = $value['order_amount'] - $value['daiyan_sale'] - $youhui_price;
                if ($order_amount < 0) {
                    $order_amount = 0.00;
                }
                $count_num = M('order_goods')->where("order_id=" . $value['order_id'])->sum('goods_num');
                $order_list[$key]['shop_num'] = $count_num;
                $order_list[$key]['order_price'] = $order_amount;
            }
            $data['order_list']=$order_list;
            $this->ajax_r('1', '成功', $data);
        } else {
            $this->ajax_r('0', '用户信息已失效');
        }
    }

    //取消订单
    public function cancel_order(){
        $order_id=I('post.order_id');
        $order=M('order');
        $uid = $this->uid;
        $store_id = $this->store_id;
        $order_info_d=$order->where('buyer_id=' . $uid . ' and  store_id='.$store_id)->find($order_id);
        $status=get_order_status($order_info_d['order_sn'],'10');
        if($status){
            $rs=$order->where('order_sn='.$order_info_d['order_sn'])->setField('order_state','0');
            if($rs){
                $this->ajax_r('1','','订单取消成功!');
            }else{
                $this->ajax_r('0','','订单取消失败!');
            }
        }else{
            $this->ajax_r('0','','订单取状态不正确');
        }
    }

    //确认收货订单
    public function confirm_order(){
        $order_id=I('post.order_id');
        $order=M('order');
        $uid = $this->uid;
        $store_id = $this->store_id;
        $order_info=$order->where('buyer_id=' . $uid . ' and  store_id='.$store_id)->find($order_id);
        $status=get_order_status($order_info['order_sn'],'30');
        if($status){
            $data['order_state']='40';
            $data['finnshed_time']=time();
            $rs=$order->where('order_id='.$order_id)->save($data);
            if($rs){
                //收货代言通知
                $uid=$order_info['buyer_id'];
                $order_add_time=$order_info['add_time'];
                $user_info=M('users')->find($uid);

                if($user_info['wx_h5openid']){
                    $openid=$user_info['wx_h5openid'];
                    $url='https://m.58daiyan.com/user/daiyan.html';
                    $keyword1=date('Y年m月d日  H:i',$order_add_time);
                    $keyword2=$order_info['order_sn'];
                    send_info_daiyan($openid,$url,$keyword1,$keyword2);
                }
                $this->ajax_r('1','确认收货成功');
            }else{
                $this->ajax_r('0','确认收货失败');
            }
        }else{
            $this->ajax_r('0','订单取状态不正确');
        }

    }
    //退款退货
    public function refund(){
        $order_id=I('post.order_id');
        $order=M('order');
        $order_info=$order->find($order_id);
        if(empty(I('post.refund_money'))){

        }
        $time=time()+60*60*24*7;
        if($_POST&&$order_info['order_state']>10&&$order_info['finnshed_time']<$time){
            $data['refund_state']='1';
            $data['refund_amount']=I('post.refund_money');
            $data['refund_reason']=I('post.refund_reason');
            $data['refund_type']=I('post.refund_type');
            $data['order_id']=I('post.order_id');
            $data['refund_time']=time();
            $rs=$order->save($data);
            if($rs){
                $this->ajax_r(1,'提交成功');
            }else{
                $this->ajax_r(0,'提交失败');
            }
        }else{
            $this->ajax_r(0,'','订单信息错误');
        }
    }
    //退款退货更新
    public function refundUpdate(){
        if($_POST){
            $data['refund_shipping_code']=I('post.wuliu_number');
            $data['refund_shipping_company_id']=I('post.wuliu_express');
            $data['refund_shipping_name']=I('post.wuliu_express_name');
            $data['order_id']=I('post.order_id');
            $order=M('order');
            $rs=$order->save($data);
            if($rs){
                $this->ajax_r(1,'','提交成功');
            }else{
                $this->ajax_r(0,'','提交失败');
            }
        }
    }
    //第一次评价
    function evaluate(){
        //print_r($_POST);
        file_put_contents("evaluate.txt", date("Y-m-d H:i:s") . "POST   " . print_r($_POST, true) . "\r\n", FILE_APPEND);
        $goodsEvaluate=json_decode($_POST['goodsEvaluate'],true);
        file_put_contents("evaluate.txt", date("Y-m-d H:i:s") . "goodsEvaluate   " . print_r($goodsEvaluate, true) . "\r\n", FILE_APPEND);

        //print_r($goodsEvaluate);
        $order_id=I('post.order_id');
        $flag=true;
        $uid = $this->uid;
        $userinfo=M('users')->find($uid);
        $order_goods_evaluate=M('order_goods_evaluate');

        foreach($goodsEvaluate as $key=>$value){
            $data=array();
            $data['order_id']=$order_id;
            $data['goods_id']=$value['goods_id'];
            $data['uid']=$uid;
            $data['content']=$value['content'];
            $data['addtime']=time();
            $data['image']=$value['imgs'];
            $data['member_name']=$userinfo['username'];
            if($value['is_anonymous']){
                $data['is_anonymous']=1;
            }else{
                $data['is_anonymous']=0;
            }
            $data['scores']=$value['scores'];
            file_put_contents("evaluate.txt", date("Y-m-d H:i:s") . "data   " . print_r($data, true) . "\r\n", FILE_APPEND);

            //print_r($data);
            $rs=$order_goods_evaluate->add($data);
            file_put_contents("evaluate.txt", date("Y-m-d H:i:s") . "sql1   " . print_r($order_goods_evaluate->getLastSql(), true) . "\r\n", FILE_APPEND);
            file_put_contents("evaluate.txt", date("Y-m-d H:i:s") . "rs1   " . print_r($rs, true) . "\r\n", FILE_APPEND);

            //print_r($order_goods_evaluate->getLastSql());
            //print_r('rs shi  '.$rs);
            if(!$rs){
                $flag=false;
            }
            aver_shop($value['order_goods_id']);
        }
        if($flag){
            $order_data['order_id']=$order_id;
            $order_data['evaluation_state']='1';
            $order=M('order');
            $rs=$order->save($order_data);
            file_put_contents("evaluate.txt", date("Y-m-d H:i:s") . "sql2   " . print_r($order->getLastSql(), true) . "\r\n", FILE_APPEND);
            file_put_contents("evaluate.txt", date("Y-m-d H:i:s") . "rs2   " . print_r($rs, true) . "\r\n", FILE_APPEND);

            if(!$rs){
                $flag=false;
            }
        }
        if($flag){
            $this->ajax_r(1,'','评论成功');
        }else{
            $this->ajax_r(0,'','评论失败');
        }
    }
    //追加评论
    function re_evaluate(){
        $goodsEvaluate=json_decode($_POST['goodsEvaluate'],true);
        $order_id=I('post.order_id');
        $flag=true;
        $order_goods_evaluate=M('order_goods_evaluate');
        foreach($goodsEvaluate as $key=>$value){
            $data=array();
            $map['order_id']=$order_id;
            $map['goods_id']=$value['order_goods_id'];
            $data['again_content']=$value['content'];
            $data['again_addtime']=time();
            $data['again_image']=$value['imgs'];
            $rs=$order_goods_evaluate->where($map)->save($data);
            if(!$rs){
                $flag=false;
            }
        }
        if($flag){
            $order_data['order_id']=$order_id;
            $order_data['evaluation_state']='2';
            $order=M('order');
            $rs=$order->save($order_data);
            if(!$rs){
                $flag=false;
            }
        }
        if($flag){
            $this->ajax_r(1,'','评论成功');
        }else{
            $this->ajax_r(0,'','评论失败');
        }
    }
    //我的收藏
    function myCollect(){
        if($_POST){
            $store_id = $this->store_id;
            $uid = $this->uid;
            $users_shopcollect=M('users_shopcollect');
            $lastId = intval(I('post.lastId'));
            $Num = trim(I('post.num', 6));
            if (!empty($lastId)) {
                $shopcollectdetails = $users_shopcollect->field('yt_users_shopcollect.id')->find($lastId);
                if (empty($shopcollectdetails)) {
                    $this->ajax_r(0, '最后ID参数错误！');
                }
                $where['_string'] = ' yt_users_shopcollect.id<"' . $lastId . '" ';
            }
            $data['shopList']=$users_shopcollect
                ->field('yt_shop.title,yt_shop.id,yt_shop.price,yt_shop.oprice,yt_shop.image,yt_users_shopcollect.id as cid')
                ->join('yt_shop ON yt_shop.id = yt_users_shopcollect.shop_id','left')
                ->where('yt_users_shopcollect.user_id='.$uid.' and yt_shop.store_id='.$store_id)
                ->order('yt_users_shopcollect.id desc')
                ->limit(0,$Num)
                ->select();
            $data['total_num']=$users_shopcollect
                ->field('yt_shop.title,yt_shop.id,yt_shop.price,yt_shop.oprice,yt_shop.image,yt_users_shopcollect.id as cid')
                ->join('yt_shop ON yt_shop.id = yt_users_shopcollect.shop_id','left')
                ->where('yt_users_shopcollect.user_id='.$uid.' and yt_shop.store_id='.$store_id)
                ->count();
            if($data['shopList']){
                $this->ajax_r(1,'成功',$data);
            }else{
                $this->ajax_r(0,'失败');
            }
        }else{
            $this->ajax_r(0,'请求错误');
        }
    }

    public function myRefundOrderList(){
        $order=M('order');
        $uid = $this->uid;
        $store_id = $this->store_id;
        $where['buyer_id']=$uid;
        $where['store_id'] = $store_id;
        $where['refund_state']=array('GT',0);
        $lastId = intval(I('post.lastId'));
        $Num = trim(I('post.num', 6));
        if (!empty($lastId)) {
            $orderdetails = $order->field('yt_order.order_id')->find($lastId);
            if (empty($orderdetails)) {
                $this->ajax_r(0, '最后ID参数错误！');
            }
            $where['_string'] = ' order_id<"' . $lastId . '" ';
        }
        $order_list=$order->where($where)->limit(0,$Num)->order('refund_state asc ,order_id desc')->select();
        foreach($order_list as $key=>$value){
            if($value['refund_state']=='1'){
                $order_list[$key]['status_describe']='申请中';
            }
            if($value['refund_state']=='2'){
                if($value['refund_type']=='1'){
                    $order_list[$key]['status_describe']='商家同意，待打款';
                }else{
                    if($value['refund_shipping_code']){
                        $order_list[$key]['status_describe']=='商家同意,待商家收货';
                    }else{
                        $order_list[$key]['status_describe']=='商家同意,待买家发货';
                    }
                }
            }
            if($value['refund_state']=='3'){
                $order_list[$key]['status_describe']=='商家拒绝';
            }
            if($value['refund_state']=='4'){
                $order_list[$key]['status_describe']=='待客服打款';
            }
            if($value['refund_state']=='5'){
                $order_list[$key]['status_describe']=='退款完成';
            }
            if($value['shipping_fee']!=0){
                $order_list[$key]['shipping_fee']='运费：￥'.$value['shipping_fee'];
            }else{
                $order_list[$key]['shipping_fee']='免邮';
            }
            $shop_list=get_order_shop($value['order_id']);
            $order_list[$key]['shop_list']=$shop_list;
            $count_num = M('order_goods')->where("order_id=" . $value['order_id'])->sum('goods_num');
            $order_list[$key]['shop_num'] = $count_num;
        }
        $data['order_list']=$order_list;
        if($order_list){
            $this->ajax_r('1', '成功', $data);
        }else{
            $this->ajax_r('0', '暂无数据');
        }

    }

    //获取用户地址信息
    public function getAddress()
    {
        $user_id = $this->uid;
        $users_address = M('users_address');
        $users_address = $users_address->where('user_id=' . $user_id )->select();
        if ($users_address) {
            foreach ($users_address as $key => $value) {
                $users_address[$key]['province'] = getProvinceInfo($value['province']);
                $users_address[$key]['city'] = getCityInfo($value['city']);
                $users_address[$key]['district'] = getDistrictInfo($value['district']);
            }
        }
        if (!empty($users_address)) {
            $this->ajax_r(1, '成功！',$users_address);
        } else {
            $this->ajax_r(0, '用户地址为空！');
        }
    }

    public function getdiyongbonus()
    {

        $daiyan = M('daiyan');
        $store_id = $this->store_id;
        $uid = $this->uid;
       /* $store_id=1;
        $uid=178;*/
        $lastId = intval(I('post.lastId'));
        $Num = trim(I('post.num', 6));
        $where['yt_daiyan.uid'] = $uid;
        $where['yt_shop.store_id'] = $store_id;
        $where['_string'] = ' yt_shop.dikouquan>0 ';
        $count = $daiyan
            ->field('yt_daiyan.*,yt_shop.image,yt_shop.title,yt_shop.dikouquan')
            ->join('yt_shop on yt_shop.id =yt_daiyan.shop_id')
            ->where($where)->count();
        if (!empty($lastId)) {
            $daiyandetails = $daiyan->field('yt_daiyan.id')->find($lastId);
            if (empty($daiyandetails)) {
                $this->ajax_r(0, '最后ID参数错误！');
            }
            $where['_string'] = ' yt_daiyan.id<"' . $lastId . '" ';
        }
        $coupon_list = $daiyan
            ->field('yt_daiyan.*,yt_shop.image,yt_shop.title,yt_shop.dikouquan')
            ->join('yt_shop on yt_shop.id =yt_daiyan.shop_id')
            ->where($where)
            ->limit(0, $Num)
            ->order('yt_daiyan.id desc')
            ->select();
        $invoice = get_web_invoice();
        foreach ($coupon_list as $key => $value) {
            $coupon_list[$key]['start_time'] = date('Y.m.d', $value['time']);
            $coupon_list[$key]['end_time'] = date('Y.m.d', $value['time'] + 60 * 60 * 24 * $invoice['web_diyong']);
            $guoqu_time = $value['time'] + 60 * 60 * 24 * $invoice['web_diyong'];
            $time = time();
            if ($time > $guoqu_time) {
                unset($coupon_list[$key]);
            }
        }
        $data['total_num'] = $count;
        $data['coupon_list'] = $coupon_list;
        if (!empty($coupon_list)) {
            $this->ajax_r(1, '成功！', $data);
        } else {
            $this->ajax_r(0, '抵用券为空！');
        }
    }
    function getDaiyanProduct(){
        $store_id = $this->store_id;
        $uid = $this->uid;

        $lastId = intval(I('post.lastId'));
        $Num = trim(I('post.num', 6));
        $where['yt_order.buyer_id'] = $uid;
        $where['yt_order.store_id'] = $store_id;
        $where['_string'] = ' (yt_order.order_state="40" and yt_order.refund_state=0 )or (yt_order.order_state="20" and yt_order.refund_state=0 and yt_order.order_type="2")';
        /*$count=M('order_goods')
            ->field('yt_shop.title,yt_shop.image,yt_shop.price,yt_shop.redenvelope,yt_shop.id')
            ->join('yt_order ON yt_order_goods.order_id = yt_order.order_id','left')
            ->join('yt_shop ON yt_order_goods.goods_id = yt_shop.id','left')
            ->where($where)
            ->group('yt_order_goods.goods_id')
            ->count();
        if (!empty($lastId)) {
            $daiyandetails = M('order_goods')->field('yt_order_goods.goods_id')->where('goods_id='.$lastId)->find();
            if (empty($daiyandetails)) {
                $this->ajax_r(0, '最后ID参数错误！');
            }
            $where['_string'] = ' yt_order_goods.goods_id<"' . $lastId . '" ';
        }*/
        $rs=M('order_goods')
            ->field('yt_shop.title,yt_shop.image,yt_shop.price,yt_shop.redenvelope,yt_shop.envelope_type,yt_shop.envelope_product_id,yt_shop.id')
            ->join('yt_order ON yt_order_goods.order_id = yt_order.order_id','left')
            ->join('yt_shop ON yt_order_goods.goods_id = yt_shop.id','left')
            ->where($where)
            ->group('yt_order_goods.goods_id')
            ->order('yt_order_goods.goods_id desc')
           // ->limit(0,$Num)
            ->select();
        if(is_array($rs)){
            foreach($rs as $k=>$v){
                if($v['envelope_type']==0){
                    $rs[$k]['jiangli']='红包：￥'.$v['redenvelope'];
                }else{
                    $envelope_product=get_shop_info($v['envelope_product_id']);
                    $rs[$k]['jiangli']='礼品：'.$envelope_product['title'];
                }
            }
        }
        $shopAngel=M('angel')
            ->field('yt_angel.*,yt_shop.*')
            ->join('yt_shop ON yt_angel.type_id = yt_shop.id','left')
            ->where("yt_angel.uid=$uid  and yt_angel.type=1 and yt_shop.store_id=$store_id")->select();
        //print_r(M('angel')->getLastSql());
        $storeAngel=M('angel')
            ->field('yt_angel.*,yt_store.*,yt_store_template.portrait')
            ->join('yt_store ON yt_angel.type_id = yt_store.id','left')
            ->join('yt_store_template ON yt_angel.type_id = yt_store_template.store_id','left')
            ->where("yt_angel.uid=$uid  and yt_angel.type=2 and yt_angel.type_id=$store_id")->select();
        //print_r(M('angel')->getLastSql());
        $typeAngel=M('angel')
            ->field('yt_angel.*,yt_ticket_type.*')
            ->join('yt_ticket_type ON yt_angel.type_id = yt_ticket_type.id','left')
            ->join('yt_shop ON FIND_IN_SET(yt_angel.type_id,yt_shop.type_id)','left')
            ->where("yt_angel.uid=$uid  and yt_angel.type=3 and yt_shop.store_id=$store_id")->select();
         //print_r(M('angel')->getLastSql());
        if(is_array($shopAngel)) {
            foreach ($shopAngel as $key => $value) {
                if ($value['envelope_type'] == 0) {
                    $shopAngel[$key]['jiangli'] = '红包：￥' . $value['redenvelope'];
                } else {
                    $envelope_product = get_shop_info($value['envelope_product_id']);
                    $shopAngel[$key]['jiangli'] = '礼品：' . $envelope_product['title'];
                }
            }
        }
        $data['shopAngel']=$shopAngel;
        $data['storeAngel']=$storeAngel;
        $data['typeAngel']=$typeAngel;
        $data['daiyan']=$rs;
        $this->ajax_r(1, '成功！', $data);
    }

    public function getDaiyanAward(){
        $store_id = $this->store_id;
        $uid = $this->uid;
        $type = I('post.type',0);
        $lastId = intval(I('post.lastId'));
        $Num = trim(I('post.num', 6));
        $where['yt_order_goods.recommend_id'] = $uid;
        $where['yt_order_goods.store_id'] = $store_id;
        $where['yt_order_goods.recommend_type'] = $type;
        $where['_string'] = ' yt_order.order_state>"10" ';
        $order_goods=M('order_goods');
        $count=$order_goods
            ->join('yt_order ON yt_order_goods.order_id = yt_order.order_id','left')
            ->field("yt_order.buyer_name,yt_order.add_time,yt_order.payment_time,yt_order.shipping_time,yt_order.finnshed_time,yt_order.order_state,yt_order.refund_state,yt_order_goods.*")
            ->where($where)
            ->count();
        if (!empty($lastId)) {
            $orderGoodsdDetails = $order_goods->find($lastId);
            if (empty($orderGoodsdDetails)) {
                $this->ajax_r(0, '最后ID参数错误！');
            }
            $where['_string'] = ' yt_order_goods.rec_id<="' . $orderGoodsdDetails['rec_id'] . '" and yt_order_goods.id!='.$lastId;
        }
        $rs=$order_goods
            ->join('yt_order ON yt_order_goods.order_id = yt_order.order_id','left')
            ->field("yt_order.buyer_name,yt_order.add_time,yt_order.payment_time,yt_order.shipping_time,yt_order.finnshed_time,yt_order.order_state,yt_order.refund_state,yt_order_goods.*")
            ->where($where)
            ->limit(0,$Num)
            ->order('yt_order_goods.rec_id desc')
            ->select();
        foreach($rs as $key=>$value){
            if($value['refund_state']==0){
                if($value['order_state']==0){
                    $rs[$key]['goumai_order_status']="已取消";
                    $rs[$key]['time']='下单时间：'.date('Y-m-d',$value['add_time']);
                }
                if($value['order_state']==10){
                    $rs[$key]['goumai_order_status']="未付款";
                    $rs[$key]['time']='下单时间：'.date('Y-m-d',$value['add_time']);
                }
                if($value['order_state']==20){
                    $rs[$key]['goumai_order_status']="已付款";
                    $rs[$key]['time']='付款时间：'.date('Y-m-d',$value['payment_time']);
                }
                if($value['order_state']==30){
                    $rs[$key]['goumai_order_status']="已发货";
                    $rs[$key]['time']='发货时间：'.date('Y-m-d',$value['shipping_time']);
                }
                if($value['order_state']==40){
                    if($value['lock_state']==0){
                        $rs[$key]['goumai_order_status']="已收货";
                        $rs[$key]['time']='收货时间：'.date('Y-m-d',$value['finnshed_time']);
                    }
                    if($value['lock_state']==1){
                        $rs[$key]['goumai_order_status']="已入账";
                        $rs[$key]['time']='收货时间：'.date('Y-m-d',$value['finnshed_time']);
                    }
                }
            }else{
                if($value['refund_state']==1) $rs[$key]['goumai_order_status']="申请退款";
                if($value['refund_state']==2) $rs[$key]['goumai_order_status']="同意退款";
                if($value['refund_state']==3) $rs[$key]['goumai_order_status']="拒绝退款";
                if($value['refund_state']==4) $rs[$key]['goumai_order_status']="退款完成";

            }
            if($value['recommend_type']==1) {
                $rs[$key]['lp_shop_info'] = M('shop')->find($value['recommend_shop_id']);
                if ($value['recommend_orderid']) {
                    $order2 = M('order')->find($value['recommend_orderid']);
                    if ($order2['order_state'] == 0) {
                        $rs[$key]['award_order_status'] = "未领取";
                    }
                    if ($order2['order_state'] == 10) {
                        $rs[$key]['award_order_status'] = "未领取";
                    }
                    if ($order2['order_state'] == 20) {
                        $rs[$key]['award_order_status'] = "已领取,待发货";
                    }
                    if ($order2['order_state'] == 30) {
                        $rs[$key]['award_order_status'] = "已发货";
                    }
                    if ($order2['order_state'] == 40) {
                        if ($order2['lock_state'] == 0) {
                            $rs[$key]['award_order_status'] = "已收货";
                        }
                        if ($order2['lock_state'] == 1) {
                            $rs[$key]['award_order_status'] = "已入账";
                        }
                    }
                } else {
                    if ($value['order_state'] > 10) {
                        $rs[$key]['award_order_status'] = '未领取';
                    } else {
                        $rs[$key]['tishi'] = "'该推荐用户还未付款，不能领取。'";
                        $rs[$key]['award_order_status'] = '未领取';
                    }
                }
            }
        }
        $data['total_num']=$count;
        $data['DaiynAwardList']=$rs;
        $this->ajax_r(1, '成功！', $data);

    }

    function get_lipin(){
        $order_data=I('post.');
        $store_id = $this->store_id;
        $uid = $this->uid;
        //匹配礼品领取人 与登陆用户是否一个
        $tuij_order_good=M('order_goods')->find($order_data['rec_id']);
        $tuij_order=M('order')->find($tuij_order_good['order_id']);
        if($tuij_order['store_id']!==$store_id){
            $this->ajax_r(0,'店铺不匹配');
        }
        if($tuij_order['order_state']<20){
            $this->ajax_r(0,'该推荐用户订单未支付.');
        }
        if($tuij_order_good['recommend_id']!=$uid){
            $this->ajax_r(0,'该订单 推荐用户不是您，不可领取礼品？');
        }
        if($tuij_order_good['recommend_orderid']>0){
            $this->ajax_r(0,'礼品已领取');
        }


        //礼品
        $result= M('shop')->find($order_data['recommend_shop_id']);
        $user_info=M('users')->find($uid);
        if($user_info['phone']==null){
            $this->ajax_r(0,'请先去个人中心-关联账户中绑定手机');
        }
        //总订单号
        $order_cn = $this->build_order_no();

        //获取收货地址
        $user_address=get_user_address($uid);
        if($user_address==null){
            $this->ajax_r(0,'请添加收货地址');
        }
        if($result&&$uid){
            $data=array();
            $store_info=get_store($result['store_id']);
            //订单总编号
            $data['order_cn']=$order_cn;
            $order_sn = $this->build_order_no();
            //订单子编号
            $data['order_sn']=$order_sn;
            $data['pay_sn']=$order_sn;
            //卖家店铺id
            $data['store_id']=$result['store_id'];
            //卖家店铺名称
            $data['store_name']=$store_info['title'];
            //买家id
            $data['buyer_id']=$uid;
            //买家收货地址ID
            $data['buyer_address_id']=$user_address['address_id'];
            //收货姓名
            $data['buyer_name']=$user_address['consigner'];
            //收货省
            $data['buyer_province']=$user_address['province'];
            //收货市
            $data['buyer_city']=$user_address['city'];
            //收货区域
            $data['buyer_district']=$user_address['district'];
            //收货地址
            $data['buyer_address']=$user_address['address'];
            //收货手机
            $data['buyer_mobile']=$user_address['mobile'];
            //收货电话
            $data['buyer_phone']=$user_address['phone'];
            //收货邮编
            $data['buyer_zip_code']=$user_address['zip_code'];
            //订单生成时间
            $data['add_time']=time();
            //1WEB2mobile
            $data['order_from']=1;
            //商品总价格
            $data['goods_amount']=0;
            //订单总价格
            $data['order_amount']=0;
            //运费
            $data['shipping_fee']=0;
            $data['order_state']='20';
            $data['payment_code']='礼品领取';
            $data['payment_time']=time();
            $data['order_type']=1;
            $data['daiyan_sale']=0;
            if($_POST){
                //留言
                $data['leavemessage']=I('post.leavemessage');
                $order=M('order');
                $cart=M('cart');
                $order_goods=M('order_goods');
                //开启事物
                $order->startTrans();
                $cart->startTrans();
                $order_goods->startTrans();
                //判断条件
                $falg=true;
                $rs_order=$order->add($data);

                if(!$rs_order){
                    $falg=false;
                }

                $order_good['order_id']=$rs_order;
                $order_good['goods_id']=$result['id'];
                $order_good['goods_name']=$result['title'];
                $order_good['goods_price']=0;
                $order_good['goods_num']=$order_data['recommend_shop_num'];

                $order_good['goods_image']=$result['image'];
                $order_good['goods_pay_price']=0;
                $order_good['goods_sku']=0;
                $order_good['goods_sku_spec']=0;
                $order_good['goods_sku_style']=0;
                $order_good['store_id']=$result['store_id'];
                $order_good['buyer_id']=$uid;
                $order_good['goods_type']=5;
                $order_good['freight']=0;
                $rs_good=$order_goods->add($order_good);

                if(!$rs_good){
                    $falg=false;
                }
            }

            if($falg){
                $order_g_info['rec_id']=$order_data['rec_id'];
                $order_g_info['recommend_orderid']=$rs_order;
                M('order_goods')->save($order_g_info);
                $order->commit();
                $cart->commit();
                $order_goods->commit();

                $this->ajax_r(1,'领取成功',$data['order_cn']);
            }else{
                $order->rollback();
                $cart->rollback();
                $order_goods->rollback();
                $this->ajax_r(0,'领取失败');
            }

        }
    }
    //获取提现信息
    function getTixianInfo(){
        $store_id = $this->store_id;
        $uid =$this->uid;
        $users_log=M('users_log');
        $rs=$users_log->where("uid=$uid  and  store_id=$store_id")->order('id desc')->select();
        foreach($rs as $key=>$value){
            $rs[$key]['status']=get_withdrawal($value['id']);
        }
        $this->ajax_r(1, '成功！', $rs);
    }
    //提现
    function tixian(){
        $store_id = $this->store_id;
        $uid = $this->uid;
        $money = I('post.money');
        //$cardId = I('post.cardId');
        $code = I('post.code');
        $data=I('post.');
        //$get_web_invoice=$this->get_web_invoice();
        $userinfo=M('users')->find($uid);
        file_put_contents("tixian.txt", date("Y-m-d H:i:s") . "post:   " .print_r($_POST, true). "\r\n", FILE_APPEND);
        if($data['tx_money']>$userinfo['money']){
            $this->ajax_r(2,'提现金额必须小于可提金额');
        }
        /*if($data['tx_money']<$get_web_invoice['web_tixian_user']){
            $this->ajax_r(3,'提现金额必须大于最低提现金额');
        }*/
        $trade_no=$this->build_order_no();
        $log['uid']=$uid;
        $log['addtime']=time();
        $log['money']=$money;
        $log['type']=0;
        $log['other']='用户提现';
        $log['money_type']=3;
        $log['store_id']=$store_id;
        $log['order_id']=$trade_no;
        $log['member_id']==$this->member_id;;
        $users_log=M('users_log');
        file_put_contents("tixian.txt", date("Y-m-d H:i:s") . "log:   " .print_r($log, true). "\r\n", FILE_APPEND);
        $log_rs=$users_log->add($log);
        file_put_contents("tixian.txt", date("Y-m-d H:i:s") . "log_rs:   " .print_r($log_rs, true). "\r\n", FILE_APPEND);

        //=========步骤1：网页授权获取用户openid============
        $openIdResult = $this->getOpenId($code, $store_id);
        if (empty($openIdResult['errcode'])) {
            $openid = $openIdResult['openid'];
        } else {
            die(json_encode($openIdResult));
        }
        file_put_contents("tixian.txt", date("Y-m-d H:i:s") . "openid:   " .print_r($openid, true). "\r\n", FILE_APPEND);
        //获取小程序配置信息
        $options   =   D('options');
        $option_name='wx_store_'.$store_id;
        $w_data['option_name']=$option_name;
        $new_w_data=$options->where($w_data)->find();
        $w_config=json_decode($new_w_data['option_value']);
        $smallRoutineInfo=get_object_vars($w_config);
        $appid = $smallRoutineInfo['APP_KEY'];
        $mch_id =$smallRoutineInfo['MCHID'];
        $key = $smallRoutineInfo['MCHID_KEY'];
        //file_put_contents("pay.txt", date("Y-m-d H:i:s") . "total_fee   " .print_r($count_price*100, true). "\r\n", FILE_APPEND);
        //=========步骤2：提现接口============
        //使用提现接口
        $withdraw = new \Withdraw_pub();

        //设置统一支付接口参数
        //设置必填参数
        //noncestr已填,商户无需重复填写
        //spbill_create_ip已填,商户无需重复填写
        //sign已填,商户无需重复填写

        //设置统一支付接口参数
        //设置必填参数

        file_put_contents("tixian.txt", date("Y-m-d H:i:s") . "tixian接口  " . "\r\n", FILE_APPEND);
        file_put_contents("tixian.txt", date("Y-m-d H:i:s") . "appid  " . print_r($appid, true) . "\r\n", FILE_APPEND);
        file_put_contents("tixian.txt", date("Y-m-d H:i:s") . "mch_id  " . print_r($mch_id, true) . "\r\n", FILE_APPEND);
        file_put_contents("tixian.txt", date("Y-m-d H:i:s") . "key  " . print_r($key, true) . "\r\n", FILE_APPEND);
        $withdraw->setAPPID($appid);
        $withdraw->setMCHID($mch_id);
        $withdraw->setMCHKEY($key);
        $withdraw->setParameter("mch_appid", $appid);//商户账号appid
        $withdraw->setParameter("mchid", $mch_id);//商户号
        $withdraw->setParameter("partner_trade_no", $trade_no);//商户订单号
        $withdraw->setParameter("openid", $openid);//用户openid
        $withdraw->setParameter("check_name",'NO_CHECK');//校验用户姓名选项
        $withdraw->setParameter("amount", $money*100);//金额
        $withdraw->setParameter("desc", '提现');//企业付款描述信息
        //非必填参数，商户可根据实际情况选填
        //$withdraw->setParameter("re_user_name","XXXX");//收款用户姓名
        //$withdraw->setParameter("device_info","XXXX");//设备号
        $result=$withdraw->getResult();
        file_put_contents("tixian.txt", date("Y-m-d H:i:s") . "result:   " .print_r($result, true). "\r\n", FILE_APPEND);
        if($result['return_code']=='SUCCESS'){
            $info['uid']=$uid;
            $info['money']=$money;
            $info['order_num']=$trade_no;
            $info['time']=time();
            $info['status']=3;
            $info['type']=1;
            $info['log_id']=$log_rs;
            $info['reason']='无';
            file_put_contents("tixian.txt", date("Y-m-d H:i:s") . "info:   " .print_r($info, true). "\r\n", FILE_APPEND);
            M('users_getmoney')->add($info);
            file_put_contents("tixian.txt", date("Y-m-d H:i:s") . "sql:   " .print_r(M('users_getmoney')->getLastSql(), true). "\r\n", FILE_APPEND);
            M('users')->where('id='.$uid)->setDec('money',$money);
            $this->ajax_r(1,'提现成功');
        }else{
            $this->ajax_r(0,$result['return_msg']);
        }
    }
    //充值
    function recharge()
    {
        if ($_POST) {
            $store_id = $this->store_id;
            $uid = $this->uid;
            $token = I('post.token');
            $cardId = I('post.cardId');
            $money = I('post.money');
            $code = I('post.code');
            $trade_no=$this->build_order_no();
            $log['uid']=$uid;
            $log['addtime']=time();
            $log['money']=$money;
            $log['type']=1;
            $log['other']='充值';
            $log['money_type']=4;
            $log['store_id']=$store_id;
            $log['member_id']=$this->member_id;
            $log['order_id']=$trade_no;
            $users_log=M('users_log');
            file_put_contents("recharge.txt", date("Y-m-d H:i:s") . "log:   " .print_r($log, true). "\r\n", FILE_APPEND);
            $log_rs=$users_log->add($log);
            file_put_contents("recharge.txt", date("Y-m-d H:i:s") . "log_rs:   " .print_r($log_rs, true). "\r\n", FILE_APPEND);
            if($log_rs){
                $store = M('store');
                $store_info = $store->find($store_id);
                $store_name = $store_info['title'];
                //=========步骤1：网页授权获取用户openid============
                $openIdResult = $this->getOpenId($code, $store_id);
                if (empty($openIdResult['errcode'])) {
                    $openid = $openIdResult['openid'];
                } else {
                    die(json_encode($openIdResult));
                }
                file_put_contents("recharge.txt", date("Y-m-d H:i:s") . "openid   " .print_r($openid, true). "\r\n", FILE_APPEND);
                //=========步骤2：使用统一支付接口，获取prepay_id============
                //使用统一支付接口
                $unifiedOrder = new \UnifiedOrder_pub();
                /*此处做数据库的查询  这里操作数据库把产品信息显示出来*/

                //设置统一支付接口参数
                //设置必填参数
                //appid已填,商户无需重复填写
                //mch_id已填,商户无需重复填写
                //noncestr已填,商户无需重复填写
                //spbill_create_ip已填,商户无需重复填写
                //sign已填,商户无需重复填写
                //

                //设置统一支付接口参数
                //设置必填参数
                $options   =   D('options');
                $option_name='wx_store_'.$store_id;
                //获取小程序配置
                $w_data['option_name']=$option_name;
                $new_w_data=$options->where($w_data)->find();
                $w_config=json_decode($new_w_data['option_value']);
                $smallRoutineInfo=get_object_vars($w_config);
                $appid = $smallRoutineInfo['APP_KEY'];
                $mch_id =$smallRoutineInfo['MCHID'];
                $key = $smallRoutineInfo['MCHID_KEY'];
                file_put_contents("recharge.txt", date("Y-m-d H:i:s") . "recharge接口  " . "\r\n", FILE_APPEND);
                file_put_contents("recharge.txt", date("Y-m-d H:i:s") . "appid  " . print_r($appid, true) . "\r\n", FILE_APPEND);
                file_put_contents("recharge.txt", date("Y-m-d H:i:s") . "mch_id  " . print_r($mch_id, true) . "\r\n", FILE_APPEND);
                file_put_contents("recharge.txt", date("Y-m-d H:i:s") . "key  " . print_r($key, true) . "\r\n", FILE_APPEND);

                $unifiedOrder->setAPPID($appid);
                $unifiedOrder->setMCHID($mch_id);
                $unifiedOrder->setMCHKEY($key);
                $unifiedOrder->setParameter("appid", $appid);//APPID
                $unifiedOrder->setParameter("mch_id", $mch_id);//商户号$openid
                //$unifiedOrder->setParameter("key",$key);//APPID
                //$unifiedOrder->setParameter("openid",$openid);//openid
                $unifiedOrder->setParameter("openid", $openid);//openid
                $unifiedOrder->setParameter("body", $store_name);//商品描述
                //自定义订单号，此处仅作举例
                $unifiedOrder->setParameter("out_trade_no", $trade_no);//商户订单号
                $unifiedOrder->setParameter("total_fee", $money*100);//总金额
                $unifiedOrder->setParameter("notify_url", 'https://m.58daiyan.com/UsersApi/rechargeNotify');//通知地址
                $unifiedOrder->setParameter("trade_type", "JSAPI");//交易类型
                //非必填参数，商户可根据实际情况选填
                //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
                //$unifiedOrder->setParameter("device_info","XXXX");//设备号
                $unifiedOrder->setParameter("attach", $token);//附加数据
                //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
                //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
                //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
                //$unifiedOrder->setParameter("openid","XXXX");//用户标识
                //$unifiedOrder->setParameter("product_id","XXXX");//商品ID


                // print_r($unifiedOrderResult);
                //从统一支付接口获取到code_url(二维码)

                //商户自行增加处理流程
                //......
                //file_put_contents("sign.txt", date("Y-m-d H:i:s") . "unifiedOrder接口   " .print_r('unifiedOrder接口', true). "\r\n", FILE_APPEND);


                $prepay_id = $unifiedOrder->getPrepayId();
                //$prepay_id = $unifiedOrder->getRoutinePrepayId($appid,$mch_id,$key);
                if ($prepay_id['return_code'] == 'FAIL') {
                    $this->ajax_r(0, $prepay_id['return_msg']);
                }
                //$prepay_id=$prepay_id['prepay_id'];
                // print_r($prepay_id);

                // echo $prepay_id;exit();
                //=========步骤3：使用jsapi调起支付============
                 file_put_contents("recharge.txt", date("Y-m-d H:i:s") . "JsApi_pub接口   " .print_r('JsApi_pub接口', true). "\r\n", FILE_APPEND);

                $jsApi = new \JsApi_pub();
                $jsApi->setAPPID($appid);
                $jsApi->setMCHID($mch_id);
                $jsApi->setMCHKEY($key);
                $jsApi->setPrepayId($prepay_id);

                $jsApiParameters = $jsApi->getParameters();
                file_put_contents("recharge.txt", date("Y-m-d H:i:s") . "jsApiObj   " .print_r($jsApiParameters, true). "\r\n", FILE_APPEND);

                //print_r($jsApiParameters);
                $data = (array)json_decode($jsApiParameters);
                 file_put_contents("recharge.txt", date("Y-m-d H:i:s") . "data   " .print_r($data, true). "\r\n", FILE_APPEND);

                unset($data['appId']);
                $this->ajax_r(1, '成功！', $data);
            }

        }
    }
    //充值通知
    public function rechargeNotify()
    {
        //使用通用通知接口
        $notify = new \Notify_pub();
        //存储微信的回调
        // $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $xml = file_get_contents('php://input');
        //file_put_contents("rechargeNotify.txt", date("Y-m-d H:i:s") . "xml:   " .print_r($xml, true). "\r\n", FILE_APPEND);
        $redis = connectRedis();
        $parameter = $notify->xmlToArray($xml);
        //file_put_contents("rechargeNotify.txt", date("Y-m-d H:i:s") . "parameter:   " .print_r($parameter, true). "\r\n", FILE_APPEND);

        $token = $parameter['attach'];
        //file_put_contents("rechargeNotify.txt", date("Y-m-d H:i:s") . "token:   " .print_r($token, true). "\r\n", FILE_APPEND);
        $storeString = $token . 'storeId';
        $store_id = $redis->get($storeString);
        //file_put_contents("rechargeNotify.txt", date("Y-m-d H:i:s") . "store_id:   " .print_r($store_id, true). "\r\n", FILE_APPEND);
        $options   =   D('options');
        $option_name='wx_store_'.$store_id;
        //获取小程序配置
        $w_data['option_name']=$option_name;
        $new_w_data=$options->where($w_data)->find();
        $w_config=json_decode($new_w_data['option_value']);
        $smallRoutineInfo=get_object_vars($w_config);
        $appid = $smallRoutineInfo['APP_KEY'];
        $mch_id =$smallRoutineInfo['MCHID'];
        $key = $smallRoutineInfo['MCHID_KEY'];
        $notify->setAPPID($appid);
        $notify->setMCHID($mch_id);
        $notify->setMCHKEY($key);
        $notify->saveData($xml);
        // var_dump($xml);
        //验证签名，并回应微信。
        //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
        //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
        //尽可能提高通知的成功率，但微信不保证通知最终能成功。
        if ($notify->checkSign() == FALSE) {
            $notify->setReturnParameter("return_code", "FAIL");//返回状态码
            $notify->setReturnParameter("return_msg", "签名失败");//返回信息
        } else {
            $notify->setReturnParameter("return_code", "SUCCESS");//设置返回码
        }
        $returnXml = $notify->returnXml();

        $out_trade_no = $parameter['out_trade_no'];
        $out_trade_no = explode('_', $out_trade_no);
        $out_trade_no = $out_trade_no[0];
        //==商户根据实际情况设置相应的处理流程，此处仅作举例=======

        //以log文件形式记录回调信息
        //         $log_ = new Log_();
        $log_name = __ROOT__ . "/notify_url.log";//log文件路径
        log_result($log_name, "【接收到的notify通知】:\n" . $xml . "\n");

        if ($notify->checkSign() == TRUE) {
            if ($notify->data["return_code"] == "FAIL") {
                //此处应该更新一下订单状态，商户自行增删操作
                log_result($log_name, "【通信出错】:\n" . $xml . "\n");
                echo 'error';
            } elseif ($notify->data["result_code"] == "FAIL") {
                //此处应该更新一下订单状态，商户自行增删操作
                log_result($log_name, "【业务出错】:\n" . $xml . "\n");
                echo 'error';
            } else {
                //此处应该更新一下订单状态，商户自行增删操作
                $res = $notify->data["result_code"];
                //file_put_contents("rechargeNotify.txt", date("Y-m-d H:i:s") . "res:   " .print_r($res, true). "\r\n", FILE_APPEND);
                switch ($res) {
                    case 'SUCCESS';
                        //file_put_contents("rechargeNotify.txt", date("Y-m-d H:i:s") . "out_trade_no:   " .print_r($out_trade_no, true). "\r\n", FILE_APPEND);
                        $status = M('users_log')->where('order_id="'.$out_trade_no.'"')->find();
                        //file_put_contents("rechargeNotify.txt", date("Y-m-d H:i:s") . "sql:   " .print_r( M('users_log')->getLastSql(), true). "\r\n", FILE_APPEND);
                        //file_put_contents("rechargeNotify.txt", date("Y-m-d H:i:s") . "status:   " .print_r($status, true). "\r\n", FILE_APPEND);
                        if ($status) {
                            $members=M('member')->find($status['member_id']);
                            //file_put_contents("rechargeNotify.txt", date("Y-m-d H:i:s") . "members:   " .print_r($members, true). "\r\n", FILE_APPEND);
                            $data['money']=$members['money']+$status['money'];
                            $data['id']=$status['member_id'];
                            //file_put_contents("rechargeNotify.txt", date("Y-m-d H:i:s") . "data:   " .print_r($data, true). "\r\n", FILE_APPEND);
                            M('member')->save($data);
                            //file_put_contents("rechargeNotify.txt", date("Y-m-d H:i:s") . "sql2:   " .print_r(M('member')->getLastSql(), true). "\r\n", FILE_APPEND);
                            //update_order_status($out_trade_no, $out_trade_no, '20', '微信');
                        }
                        log_result($log_name, "【支付成功】:\n" . $xml . "\n");
                        echo 'SUCCESS';
                        break;
                    case 'NOTPAY';
                        echo 'NOTPAY';
                        break;
                    default:
                        echo 'ERROR';
                        break;
                }
            }
        }
    }
    //获取openId
    public function getOpenId($code, $store_id)
    {
        $options   =   D('options');
        $option_name='wx_store_'.$store_id;
        //获取小程序配置
        $w_data['option_name']=$option_name;
        $new_w_data=$options->where($w_data)->find();
        $w_config=json_decode($new_w_data['option_value']);
        $smallRoutineInfo=get_object_vars($w_config);
        $appid = $smallRoutineInfo['APP_KEY'];
        $appsecret =$smallRoutineInfo['APP_SECRET'];
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $appsecret . '&js_code=' . $code . '&grant_type=authorization_code';
        file_put_contents("pay.txt", date("Y-m-d H:i:s") . "url   " . print_r($url, true) . "\r\n", FILE_APPEND);
        $rs1 = file_get_contents($url);
        $rs = json_decode($rs1, TRUE);
        file_put_contents("pay.txt", date("Y-m-d H:i:s") . "rs   " . print_r($rs, true) . "\r\n", FILE_APPEND);
        //\Think\Log::write("session :\n" . print_r($rs, true) . "\n",'storeApi/session' . date('Y-m-d'));
        if (empty($rs['errcode'])) {
            $redis = connectRedis();
            $redis->set('session_key', $rs['session_key']);
            $redis->set('openid', $rs['openid']);
            return $rs;
        } else {
            return $rs;
        }
    }
    public function build_order_no()
    {
        $no = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        //检测是否存在
        $db = M('order');
        $info = $db->where(array('order_sn'=>$no))->find();
        (!empty($info)) && $no = $this->build_order_no();
        return $no;

    }
    public function ajax_r($status = '0', $message = '', $data = '')
    {
        $datas['status'] = $status;
        $datas['message'] = $message;
        $datas['data'] = $data;
        $datas = json_encode($datas);
        die($datas);
    }
}

?>
